package com.neu.util;

import android.content.ContentProvider;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;

import org.litepal.LitePal;

public class MyContentProvider extends ContentProvider {

    public static final int QUERY_SUCCESS = 0;
    public static final int UPDATE_SUCCESS = 1;
    public static final int DELETE_SUCCESS = 2;
    public static final int INSERT_SUCCESS = 3;

    private SQLiteDatabase db;

    public static final String AUTHORITY = "com.neu.provider.my";

    // UriMatcher 是一个工具类，用于帮助内容提供者匹配 URIs
    private static final UriMatcher MURI_MATCHER = new UriMatcher(UriMatcher.NO_MATCH);
    // 添加路径匹配规则
    static {
        // 添加一个 path(匹配规则)，如果匹配成功会返回 code 值。
        // authority：主机名（我们可以自己定义，随意写，当使用内容解析者时会使用到）
        // path：路径，一般是操作名称
        // code：匹配码
        MURI_MATCHER.addURI(AUTHORITY, "insert", INSERT_SUCCESS);
        MURI_MATCHER.addURI(AUTHORITY, "delete", DELETE_SUCCESS);
        MURI_MATCHER.addURI(AUTHORITY, "update", UPDATE_SUCCESS);
        MURI_MATCHER.addURI(AUTHORITY, "query", QUERY_SUCCESS);
    }

    public MyContentProvider() {
    }

    @Override
    public int delete(Uri uri, String selection, String[] selectionArgs) {
        // Implement this to handle requests to delete one or more rows.
        throw new UnsupportedOperationException("Not yet implemented");
    }

    @Override
    public String getType(Uri uri) {
        // TODO: Implement this to handle requests for the MIME type of the data
        // at the given URI.
        throw new UnsupportedOperationException("Not yet implemented");
    }

    @Override
    public Uri insert(Uri uri, ContentValues values) {
        if(INSERT_SUCCESS == MURI_MATCHER.match(uri)){
            long id = db.insert("student", null, values);
            return ContentUris.withAppendedId(uri, id);
        }
        throw new UnsupportedOperationException("Not yet implemented");
    }

    @Override
    public boolean onCreate() {
        LitePal.initialize(getContext());
        db=LitePal.getDatabase();
        return true;
    }

    @Override
    public Cursor query(Uri uri, String[] projection, String selection,
                        String[] selectionArgs, String sortOrder) {
        // TODO: Implement this to handle query requests from clients.
        throw new UnsupportedOperationException("Not yet implemented");
    }

    @Override
    public int update(Uri uri, ContentValues values, String selection,
                      String[] selectionArgs) {
        // TODO: Implement this to handle requests to update one or more rows.
        throw new UnsupportedOperationException("Not yet implemented");
    }
}
